package com.example.api.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class HttpUtils {

    private static final RestTemplate REST_TEMPLATE = new RestTemplate();

    public static String post(HttpRequest httpRequest) {
        return post(httpRequest.getUrl(),
                httpRequest.getHttpHeaders(),
                httpRequest.getUriParameters(),
                httpRequest.getBodyParameters(),
                String.class);
    }

    private static <T> T post(String url, HttpHeaders httpHeaders, JSONObject uriParameters, JSONObject bodyParameters, Class<T> clazz) {
        if (StringUtils.isBlank(url)) {
            throw new RuntimeException("请求URL不能为空");
        }
        if (httpHeaders == null) {
            httpHeaders = new HttpHeaders();
            httpHeaders.add("Content-Type", "application/json; charset=utf-8");
        }
        HttpEntity<String> httpEntity = new HttpEntity<>(JSON.toJSONString(bodyParameters), httpHeaders);
        ResponseEntity<T> responseEntity = REST_TEMPLATE.postForEntity(url, httpEntity, clazz, JSON.toJSONString(uriParameters));
        HttpStatus statusCode = responseEntity.getStatusCode();
        T body = responseEntity.getBody();
        if (statusCode != HttpStatus.OK) {
            log.info("===== POST请求失败 开始 =====");
            log.info("## 请求路径：[{}]", url);
            log.info("## 请求路径参数：[{}]", uriParameters);
            log.info("## 请求体参数：[{}]", bodyParameters);
            log.info("## 响应码：[{}]", statusCode);
            log.info("## 响应体：[{}]", JSON.toJSONString(body));
            log.info("===== POST请求失败 结束 =====");
            throw new RuntimeException("获取飞书AccessToken失败");
        }
        log.info("===== POST请求成功 开始 =====");
        log.info("## 请求路径：[{}]", url);
        log.info("## 请求路径参数：[{}]", uriParameters);
        log.info("## 请求体参数：[{}]", bodyParameters);
        log.info("## 响应码：[{}]", statusCode);
        log.info("## 响应体：[{}]", JSON.toJSONString(body));
        log.info("===== POST请求成功 结束 =====");
        return body;
    }

    @Data
    public static class HttpRequest {

        /**
         * 请求URL
         */
        private String url;

        /**
         * URL后面的参数
         */
        private JSONObject uriParameters;

        /**
         * 请求体中的参数
         */
        private JSONObject bodyParameters;

        /**
         * 请求头
         */
        private HttpHeaders httpHeaders;

        /**
         * 返回的响应体类型
         */
        private Class<?> clazz;
    }

}
